package net.linku.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.common.exceptions.UnauthorizedClientException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

/**
 * 自定义异常处理器，用于处理OAuth2异常
 */
@Component
public class CustomExceptionTranslator implements WebResponseExceptionTranslator<OAuth2Exception> {

    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
        // 处理用户名未找到异常
        if (e instanceof UsernameNotFoundException) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new OAuth2Exception(e.getMessage()));
        }
        // 处理认证异常
        else if (e instanceof AuthenticationException) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new OAuth2Exception("认证失败：" + e.getMessage()));
        }
        // 处理未授权客户端异常
        else if (e instanceof UnauthorizedClientException) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new OAuth2Exception(e.getMessage()));
        }
        // 处理无效的授权异常
        else if (e instanceof InvalidGrantException) {
            if ("Bad credentials".equals(e.getMessage())) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new OAuth2Exception("用户名或密码错误"));
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new OAuth2Exception(e.getMessage()));
            }
        } else {
            // 处理其他异常
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new OAuth2Exception("服务端错误：" + e.getMessage()));
        }
    }
}
